package com.ccom.test.delayQueueTest;

import org.jetbrains.annotations.NotNull;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description: DelayEntity实现延时队列测试
 * @author: jjzhang24
 * @date: 2022年01月05日
 */
public class DelayEntity implements Delayed {

    public static void test(String[] args) throws InterruptedException {
        DelayQueue<DelayEntity> delayEntities = new DelayQueue<>();
        DelayEntity d1 = new DelayEntity("msg1",System.currentTimeMillis()+2000);
        DelayEntity d2 = new DelayEntity("msg2",System.currentTimeMillis()+6000);
        DelayEntity d3 = new DelayEntity("msg3",System.currentTimeMillis()+4000);
        DelayEntity d4 = new DelayEntity("msg4",System.currentTimeMillis()+10000);
        DelayEntity d5 = new DelayEntity("msg5",System.currentTimeMillis()+7000);
        DelayEntity d6 = new DelayEntity("msg6",System.currentTimeMillis()-1000);
        delayEntities.add(d1);
        delayEntities.add(d2);
        delayEntities.add(d3);
        delayEntities.add(d4);
        delayEntities.add(d5);
        delayEntities.add(d6);
        System.out.println(delayEntities.take().msg);
        System.out.println(delayEntities.take().msg);
        System.out.println(delayEntities.take().msg);
        System.out.println(delayEntities.take().msg);
        System.out.println(delayEntities.take().msg);
        System.out.println(delayEntities.take().msg);
    }

    private String msg;

    private long time;

    public DelayEntity(String msg, long time) {
        this.msg = msg;
        this.time = time;
    }

    @Override
    public long getDelay(@NotNull TimeUnit unit) {
        return unit.convert(time-System.currentTimeMillis(),TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(@NotNull Delayed o) {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS)-o.getDelay(TimeUnit.MILLISECONDS));
    }
}
